/**
 *	react router code split
 * */
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { injectIntl, intlShape } from 'react-intl';
import { Spin } from 'antd';

// NProgress 引入及配置
import 'nprogress/nprogress.css';
import NProgress from 'nprogress';

import { JSLoad, JSFailLoad, dataLoad } from './LoadIcon';

NProgress.configure({
  showSpinner: false
});

/**
 *	异步路由加载
 * 默认注入 mobx('global','language') 和国际化  intl
 * 默认 mobx observer
 * importComponent Promise () => import()
 * withSpin default true
 * */
const LazyRoute = (importComponent, withSpin = true) => {
  @inject('global', 'language')
  @observer
  class RouteComponent extends Component {
    constructor(props) {
      super(props);
      this.state = {
        Dom: null,
        tip: null,
        loadingIcon: JSLoad,
        loading: false
      };
      console.log(props.route);
      this.load();
    }

    load = () => {
      NProgress.start();
      importComponent()
        .then(dom => {
          this.setState({
            Dom: dom.default ? dom.default : null
          });
        })
        .catch(() => {
          this.setState({
            loadingIcon: JSFailLoad,
            tip: '页面加载失败'
          });
        })
        .finally(() => {
          NProgress.done();
        });
    };

    // 显示 loading
    showLoading = (tip = null) => {
      this.setState({ loading: true, loadingIcon: dataLoad, tip });
    };

    // 隐藏 loading
    hideLoading = () => {
      this.setState({ loading: false });
    };

    render() {
      const { Dom, loading, loadingIcon, tip } = this.state;
      if (withSpin) {
        return (
          <Spin spinning={loading} indicator={loadingIcon} tip={tip}>
            {Dom ? (
              <Dom
                showPageLoading={this.showLoading}
                hidePageLoading={this.hideLoading}
                {...this.props}
              />
            ) : null}
          </Spin>
        );
      }
      return Dom ? <Dom {...this.props} /> : null;
    }
  }
  RouteComponent.propTypes = {
    intl: intlShape.isRequired
  };
  // 注入国际化 props intl
  return injectIntl(RouteComponent);
};

export default LazyRoute;
